package Service;

import DAO.UserDAO;
import DATA.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "modifyInfo", value = "/modifyInfo")
public class modifyInfo extends HttpServlet {

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("firstPassword");
        String email = req.getParameter("email");
        System.out.println(password);

        HttpSession session=req.getSession();
        String oldname=String.valueOf(session.getAttribute("user"));
        int oldid= (int) session.getAttribute("uid");
        //找名字
        User ans = null;
        try {
            ans = UserDAO.FindbyName(oldname);
        } catch (SQLException e) {
            throw new RuntimeException("修改失败");
        }
        if (ans == null) {
            //不存在即登陆已过期
            resp.getWriter().print("登录已过期，3秒后回到登录页面");
            resp.setHeader("refresh", "3;url=/Login.jsp");
            System.out.println("登陆已过期");

        } else {
            //存在则修改信息并返回个人信息页面
            //如果没有给新的，就用原来的
            if(username==""){
                username=ans.getUsername();
            }
            if(password==""){
                password=ans.getUserpwd();
            }
            if(email==""){
                email=ans.getEmail();
            }
            try {
                Boolean ifmodify=UserDAO.modify(username,password,email,oldname);
                session.removeAttribute("user");//先把登录留下的东西全部清除，再放上新的东西
                session.removeAttribute("uid");
                session.removeAttribute("Email");

                req.getSession().setAttribute("user", username);
                req.getSession().setAttribute("uid", oldid);
                req.getSession().setAttribute("Email", email);
                req.getRequestDispatcher("Homepage.jsp").forward(req,resp);

            } catch (SQLException e) {
                throw new RuntimeException("修改失败");
            }
            req.getRequestDispatcher("modifyInfo.jsp").forward(req, resp);
        }
    }
}
